<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Models\Element;
use App\Models\Student;
use App\Models\Grade;
use App\Models\Semester;
use App\Models\Details;
use App\Models\Comment;
use App\Models\VeidooScore;
use App\Models\VeidooGrades;
use Encore\Admin\Facades\Admin;

class CQETableController extends Controller
{
    public function table(Content $content)
    {
        $content->header('综合素质评价');
        $content->description(' ');

        $veidooDatas = [];
        $veidoos = DB::select("Select
v.id,v.name veidoo,count(1) sum
from cqe_veidoo v
left join cqe_element e
on v.id = e.veidoo_id 
GROUP BY v.name");

        $i = 0;
        foreach ($veidoos as $veidoo) {
            $j = 0;
            $data = [];
            $elements = Element::where('veidoo_id', $veidoo->id)->get();
            foreach ($elements as $element) {
                $data[$j]['id'] = $element->id;
                $data[$j]['element'] = $element->name;
                $data[$j]['content'] = $element->content;
                $data[$j]['score'] = $element->score;

                $j++;
            }
            $veidooDatas[$i]['id'] = $veidoo->id;
            $veidooDatas[$i]['veidoo'] = $veidoo->veidoo;
            $veidooDatas[$i]['sum'] = $veidoo->sum;
            $veidooDatas[$i]['data'] = $data;
            $i++;
        }

        $student_id = $_GET['id'];

        $student = Student::where('id', $student_id)->first();
        $grade = Grade::where('id',$student->class_id)->first();
        $semester = Semester::where('is_semester',1)->first();
        $studentData = [
            'id' =>$student->id,
            'student_id' => $student->student_id,
            'name' => $student->name,
            'class' => $grade->class_name,
            'seat' => $student->seat,
            'semester' => $semester->name
        ];
        $appraiser_type = $_GET['type'];
        $content->body(new Box('素质评价表', view('admin.cqe.CQEdetail',['veidooDatas' => $veidooDatas,'studentData' => $studentData, 'type' => $appraiser_type])));

        return $content;
    }

    public function handle(){
        foreach($_POST as $v) {
            if(empty($v)) {
                return  back()->with(admin_toastr('评分或评语不能为空...', 'warning'));
            }
        }

//        dd($_POST);

        $student_id = $_POST['student_id'];
        $appraiser_type = $_POST['appraiser_type'];
        $comment = $_POST['comment'];

        $user_id = Admin::user()->id;
        $elment_arr = [];
        $elments = Element::get();

        foreach ($elments as $elment) {
            $postId = $elment->id . '_';
            $elment_arr[$elment->id] = $_POST[$postId];
        }

        $semester = Semester::where('is_semester',1)->first();
        $semester_id = $semester->id;

        foreach ($elment_arr as $k => $v) {
            if(empty($v)) {
                $v = 0;
            }
            Details::create([
                'semester_id' => $semester_id,
                'student_id' => $student_id,
                'appraiser' => $user_id,
                'appraiser_type' => $appraiser_type,
                'element_id' => $k,
                'score' => $v,
            ]);
        }

        Comment::create([
            'semester_id' => $semester_id,
            'student_id' => $student_id,
            'evaluation_type' => $appraiser_type,
            'evaluation' => $comment
        ]);

        $veidooScores = DB::select("
select a.veidoo_id,sum(score) score from
(SELECT e.veidoo_id, d.student_id, e.id, e.name, d.score, d.appraiser_type FROM cqe_element e
left join cqe_details d
on e.id = d.element_id
where semester_id = $semester_id AND student_id = $student_id AND appraiser_type = $appraiser_type
) a
GROUP BY veidoo_id");

//        dd($veidooScores);
        foreach ($veidooScores as $veidooScore ) {
            $veidoo_id  = $veidooScore->veidoo_id;
            $score = $veidooScore->score;

            $veidoo_grade = VeidooGrades::where('veidoo_id', $veidoo_id)->where('max','>=',$score)->where('min','<=',$score)->first();
            if(!empty($veidoo_grade)) {
                $grade = $veidoo_grade->grade;
            }else {
                $grade = 'x';
            }


            VeidooScore::create([
                'semester_id' => $semester_id,
                'student_id' => $student_id,
                'veidoo_id' => $veidoo_id,
                'score' => $score,
                'grade' => $grade,
                'type' => $appraiser_type
            ]);
        }

        if ($appraiser_type == 1) {
            $url = '/admin/cqe/teacher';
        }else if($appraiser_type == 2) {
            $url = '/admin/cqe/group';
        }else {
            $url = '/admin/cqe/list';
        }

        return  redirect($url)->with(admin_toastr('保存成功...', 'success'));
    }

    public function result(Content $content)
    {
        $content->header('综合素质');
        $content->description(' ');

        $student_id = $_GET['id'];

        $student = Student::where('id', $student_id)->first();
        $grade = Grade::where('id',$student->class_id)->first();
        $semester = Semester::where('is_semester',1)->first();
        $studentData = [
            'id' =>$student->id,
            'student_id' => $student->student_id,
            'name' => $student->name,
            'class' => $grade->class_name,
            'seat' => $student->seat,
            'semester' => $semester->name
        ];

        $semester = Semester::where('is_semester', 1)->first();
        $semester_id = $semester->id;

        $stutdent_arr = VeidooScore::select(['student_id'])->where('semester_id', $semester_id)->where('student_id', $student_id)->groupBy('student_id')->get();

        $result = CommonFcController::StudentVeidooScore($stutdent_arr, $semester_id);
        $final_student_arr = $result['final_student_arr'] ;
        $weight_arr = $result['weight_arr'] ;
        $veidoo_type_arr = $result['veidoo_type_arr'] ;

        if(empty($final_student_arr)) {
            $data = [
                'message' => '所有评价还未结束',
                'url' => '../cqe/list',
                'jumpTime' => 3,
                'status' => 'status'
            ];
            return view('/admin/cqe/prompt', ['data' => $data]);
        }
        
        $veidoo_result = [];
        $chart_data = [];
        $veidoo_ratio_arr = [];
        $chart_data['labels'] = '';
        $chart_data['data'] = '';

        foreach ($weight_arr as $k => $veidoo) {
            $chart_data['labels'] .=  '"' . $veidoo['name'] . '"' . ',';
            $veidoo_result[$k]['name'] = $veidoo['name'];
            $veidoo_result[$k]['weight'] = $veidoo['weight'];
            $veidoo_result[$k]['teacher'] = isset($veidoo_type_arr[$k][1])? $veidoo_type_arr[$k][1]: 0;
            $veidoo_result[$k]['group'] =  isset($veidoo_type_arr[$k][2])? $veidoo_type_arr[$k][2]: 0;
            $veidoo_result[$k]['student'] =  isset($veidoo_type_arr[$k][3])? $veidoo_type_arr[$k][3]: 0;
            $veidoo_result[$k]['mean'] = isset($final_student_arr[$student_id]['weight'])?$final_student_arr[$student_id]['weight'][$k]:0;
//            dd($final_student_arr);

            $v_score = $veidoo_result[$k]['mean'];

            $grades = VeidooGrades::where('veidoo_id',$k)->where('max','>=',$v_score)->where('min','<=',$v_score)->first();

            if(empty($grades)) {
                $veidoo_result[$k]['grade'] = 'x';
            }else {
                $veidoo_result[$k]['grade'] = $grades->grade;
            }

            $veidoo_total = Element::where('veidoo_id', $k)->sum('score');
            $veidoo_result[$k]['total'] = $veidoo_total;
            $veidoo_ratio_arr[$k] = floor(($final_student_arr[$student_id]['weight'][$k] / $veidoo_total) * 100);
        }

        $studentData['final_score'] = $final_student_arr[$student_id]['final_score'];

        $comment_arr = [];
        $comments = Comment::where('semester_id',$semester_id)->where('student_id',$student_id)->get();
        foreach ($comments as $comment) {
            $comment_arr[$comment->evaluation_type] = $comment->evaluation;
        }
        $sum = 0;
        foreach ($veidoo_result as $veidoo) {
            $sum += $veidoo['total'] * $veidoo['weight'] ;
        }
        $ratio = $studentData['final_score'] / $sum;
        $ratio = floor($ratio * 100);
        $final_grade = '';
        $grade_color = '';
        switch ($ratio) {
            case ($ratio <= 100 && $ratio > 90) :
                $final_grade = 'S';
                $grade_color = '#FF8000';
                break;
            case ($ratio <= 90 && $ratio > 70) :
                $final_grade = 'A';
                $grade_color = '#0080FF';
                break;
            case ($ratio <= 70 && $ratio > 50) :
                $final_grade = 'B';
                $grade_color = '#B15BFF';
                break;
            case ($ratio <= 50 && $ratio > 25) :
                $final_grade = 'C';
                $grade_color = '#00BB00';
                break;
            case ($ratio <= 25 && $ratio > 0) :
                $final_grade = 'D';
                $grade_color = '#EA0000';
                break;
            default:
                $final_grade = 'X';
                $grade_color = '#9D9D9D';
                break;
        }
        $studentData['final_grade'] = $final_grade;
        $studentData['grade_color'] = $grade_color;

        foreach ($veidoo_ratio_arr as $ratio) {
            $chart_data['data'] .= $ratio . ',';
        }

        $chart_data['labels'] = rtrim($chart_data['labels'], ",");
        $chart_data['data'] = rtrim($chart_data['data'], ",");

//        dd($chart_data);
        $content->body(new Box('个人综合素质评价', view('admin.cqe.result',['studentData' => $studentData, 'veidoo_result' => $veidoo_result,'comment_arr' => $comment_arr, 'chart_data' => $chart_data])));

        return $content;
    }
}
